package com.shop.service.Impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.mapper.DtsUserAccountMapper;
import com.shop.mapper.DtsUserMapper;
import com.shop.mapper.StatMapper;
import com.shop.pojo.DtsUser;
import com.shop.pojo.DtsUserAccount;
import com.shop.service.DtsUserService;
import com.shop.service.StatService;
import com.shop.util.MyUtil;
import com.shop.vo.DayStatis;
import com.shop.vo.OrderActive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName DtsUserServiceImpl
 * @Author xiao宋
 * @Date 21:26  2022/10/13
 * @Version 1.0
 * @Description TODO
 */
@Service
public class DtsUserServiceImpl implements DtsUserService {
    @Autowired
    DtsUserMapper userMapper;
    @Autowired
    DtsUserAccountMapper userAccountMapper;
    @Autowired
    StatService statService;

    @Override
    public long getTotal() {
        LambdaQueryWrapper<DtsUser> w = new LambdaQueryWrapper<>();
        w.eq(DtsUser::getDeleted, false);
        Integer total = userMapper.selectCount(w);
        return total;
    }

    @Override
    public Map<String, Object> findByPage(Integer page, Integer limit, String sort, String order, String username, String mobile) {
        // 正好有个 DtsUser 实体类是对应的，记得把密码去掉
        IPage<DtsUser> iPage = new Page<>(page, limit);
        QueryWrapper<DtsUser> w = new QueryWrapper<>();
//        前端显示的用户名为 nickname。  并不是username
        if (!StringUtils.isEmpty(username)) {
            w.eq("nickname", username);
        }
        if (!StringUtils.isEmpty(mobile)) {
            w.eq("mobile", mobile);
        }
//        排序方式
        if ("desc".equalsIgnoreCase(order)) {
            w.orderByDesc(sort);
        } else {
            w.orderByAsc(sort);
        }

        userMapper.selectPage(iPage, w);

//        挨个遍历，把密码去掉
        List<DtsUser> adminList = iPage.getRecords();
        adminList = adminList.stream().map(dtsUser -> {
            dtsUser.setPassword("");
//            前端也没要生日。给还是不给呢
//            dtsUser.setBirthday(null);
            return dtsUser;
        }).collect(Collectors.toList());
        Map<String, Object> result = new HashMap<>();
        result.put("total", iPage.getTotal());
        result.put("items", iPage.getRecords());
        return result;
    }

//        roleMapper.update(role,new QueryWrapper<DtsRole>().eq("id",3));

    @Override
    public boolean approveAgency(DtsUserAccount account) {
        QueryWrapper<DtsUserAccount> w = new QueryWrapper<>();
//        用户部分
        DtsUser dtsUser = new DtsUser();
        dtsUser.setId(account.getUserId());
        dtsUser.setUpdateTime(new Date());
        dtsUser.setUserLevel(2);
        userMapper.updateById(dtsUser);
//      改用户账户部分数据
        account.setModifyTime(new Date());
        w.eq("user_id", account.getUserId());
        return userAccountMapper.update(account, w) > 0;
    }

    @Override
    public Integer findByName(String username) {
        QueryWrapper<DtsUser> w = new QueryWrapper<>();
        w.eq("deleted", false);
        w.eq("username", username);
        DtsUser user = userMapper.selectOne(w);
        return user.getId();
    }

    @Override
    public Map<String, Object> getUser() {
        ArrayList<Object> columns = new ArrayList<>();
        columns.add("day");
        columns.add("users");
//        List<DtsUser> list = userMapper.selectList(null);
//        获取一个月之前的用户
        List<DayStatis> userDayStatis = statService.findUserDayStatis();
//        排序
        List<String> dayData = MyUtil.fetchDaySty(userDayStatis);
        //        用户一个月之内活跃日期
        List<String> userDayData = MyUtil.fetchDaySty(userDayStatis);
//        合并一个月之内的用户活跃日期和上面的一个月之内的订单日期
        userDayData = MyUtil.unionDayDate(dayData, userDayData);

//        获取用户的数量
        List<Integer> userCnt = MyUtil.fetchCntData(userDayStatis, userDayData);

        List<OrderActive> rows = new ArrayList<>();
        for (int i = 0; i < userDayStatis.size(); i++) {
            OrderActive a = new OrderActive();
            a.setDay(dayData.get(i));
            a.setUsers(userCnt.get(i));
            rows.add(a);
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("columns", columns);// array数组
        map.put("rows", rows);// map数组
        return map;
    }

    @Override
    public Map<String, Object> getGoods() {

        ArrayList<Object> columns = new ArrayList<>();
        columns.add("day");//               day : 日期,
        columns.add("orders");//            orders : 订单量,
        columns.add("products");//          products : 下单货品数量 ,
        columns.add("amount");//            amount : 下单货品总额
        List<OrderActive> rows = new ArrayList<>();

//        查出来的是当天0点的订单活跃和对应的订单总额，订单笔数
        List<DayStatis> orderDayStatis = statService.findOrderDayStatis();
        List<DayStatis> countByOrder = statService.findCountByOrder();

//        给拿到的日期排序 排序后的订单总额
        List<String> daySty = MyUtil.fetchDaySty(orderDayStatis);
//         排序后的下单商品个数
//        List<String> listCountByOrder = MyUtil.fetchDaySty(countByOrder);

//        提取 订单的总额
        List<BigDecimal> orderAmtData = MyUtil.fetchAmtData(orderDayStatis, daySty);
//        提取订单的数量
        List<Integer> orderCnData = MyUtil.fetchCntData(orderDayStatis, daySty);
//        提取下单商品个数
        List<Integer> orderCount = MyUtil.fetchCntData(countByOrder, daySty);
        for (int i = 0; i < daySty.size(); i++) {
            OrderActive a = new OrderActive();
            a.setDay(orderDayStatis.get(i).getDayStr());
            a.setOrders(orderCnData.get(i));
            BigDecimal bigDecimal = orderAmtData.get(i);
            a.setAmount(bigDecimal);
            a.setProducts(orderCount.get(i));
            rows.add(a);
        }
//        封装数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("columns", columns);// array数组
        map.put("rows", rows);// map数组
        return map;
    }

    @Override
    public Map<String, Object> getOrderMsg() {
        ArrayList<Object> columns = new ArrayList<>();
        columns.add("day");//                   day : 日期,
        columns.add("orders");//                orders : 订单量,
        columns.add("amount");//                amount : 下单货品总额
        columns.add("customers");//             customers : 下单用户数
        columns.add("pcr");//                   客单价(平均单价)
        List<OrderActive> rows = new ArrayList<>();
//        查出来的是当天0点的订单活跃和对应的订单总额，订单笔数
        List<DayStatis> orderDayStatis = statService.findOrderDayStatis();
//        给拿到的日期排序 排序后的订单总额
        List<String> daySty = MyUtil.fetchDaySty(orderDayStatis);
//        提取 订单的总额
        List<BigDecimal> orderAmtData = MyUtil.fetchAmtData(orderDayStatis, daySty);
//        提取订单的数量
        List<Integer> orderCnData = MyUtil.fetchCntData(orderDayStatis, daySty);
//        下单用户数，是下单的 用户个数
        List<DayStatis> placeAnOrderUserCount = statService.findPlaceAnOrderUserCount();
        for (int i = 0; i < daySty.size(); i++) {
            OrderActive a = new OrderActive();
            int orders = orderCnData.get(i);
            a.setDay(orderDayStatis.get(i).getDayStr());//      日期
            a.setOrders(orders);//                  订单量
            BigDecimal bigDecimal = orderAmtData.get(i);
            a.setAmount(bigDecimal);//                          下单货品总额
            orderAmtData.get(i);
            BigDecimal Bigorders = new BigDecimal(orders);
//                              保留两位小数    四舍五入
            a.setPcr(bigDecimal.divide(Bigorders,2,BigDecimal.ROUND_HALF_UP));//                 平均单价
            a.setCustomers(placeAnOrderUserCount.get(i).getCnts());//   下单用户数
            rows.add(a);

        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("columns", columns);// array数组
        map.put("rows", rows);// map数组
        return map;
    }


}
